package middleware

import (
	"fmt"
	"net/http"
	"peilian-api/utils/encrypt"
	"peilian-api/utils/format"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	Id       string `json:"id"`
	UserName string `json:"user_name"`
	Phone    string `json:"phone"`
}

func ApiVerify() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 校验token
		// 查看是否含有token
		//fmt.Printf("ApiVerify request:%+v", c.Request)
		//fmt.Printf("ApiVerify header:%+v", c.Request.Header)

		authToken := c.Request.Header.Get("AuthenticationToken")
		if authToken == "" {
			authToken = c.Query("AuthenticationToken")
		}
		// 用于解析token
		token, _ := encrypt.RsaDecode(authToken, encrypt.APIKey)
		tokenArr := strings.Split(token, "-")
		if len(tokenArr) < 3 {
			fmt.Println(token)
			format.NewResponseJson(c).Err(http.StatusUnauthorized, "token验证失败")
			return
		}
		// 客户id
		AgentId := tokenArr[1]
		aid, err := strconv.Atoi(AgentId)
		if err != nil {
			format.NewResponseJson(c).Err(http.StatusUnauthorized, "AgentId解析失败")
			return
		}
		c.Set("aid", uint(aid))

		dateTime, _ := strconv.ParseInt(tokenArr[2], 10, 64)
		fmt.Println(dateTime)

		c.Next()

	}
}
